package com.nowcoder.controller;

import com.nowcoder.annotation.LoginRequired;
import com.nowcoder.entity.User;
import com.nowcoder.service.FollowService;
import com.nowcoder.service.LikeService;
import com.nowcoder.service.UserService;
import com.nowcoder.util.CommunityConstant;
import com.nowcoder.util.CommunityUtil;
import com.nowcoder.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.rmi.MarshalledObject;

/**
 * @author by lvshh
 * @version 1.0
 * @date 2020/4/25 15:38
 */
@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {
    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;


    /**
     * 跳转到设置页面
     * @return
     */
    @LoginRequired
    @RequestMapping(path = "/setting",method = RequestMethod.GET)
    public String getSettingPage(){
        return "/site/setting";
    }

    /**
     * 更新头像操作
     * @param headerImage 图片对象
     * @param model
     * @return
     */
    @LoginRequired
    @RequestMapping(path = "/upload",method = RequestMethod.POST)
    public String uploadHeader(MultipartFile headerImage, Model model){
        /*
            如果图片对象是空的，提示错误信息并且返回到设置页面
         */
        if (headerImage == null){
            model.addAttribute("error","您还没有选择图片");
            return "/site/setting";
        }

        /*
            判断文件名字是否正确
         */
        //获取图片文件的原式名字
        String fileName = headerImage.getOriginalFilename();
        /*
            如果没有后缀无法判断是什么类型的文件
         */
        //获得文件的后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //如果后缀为空，提示错误信息
        if (StringUtils.isBlank(suffix)){
            model.addAttribute("error","文件格式不正确");
            return "/site/setting";
        }

        //生成随机文件名
        fileName = CommunityUtil.generateUUID() + suffix;
        //确定文件存放的路径，这个路径是本地路径e:/work/data/upload/XXX.jpg
        File dest = new File(uploadPath + "/" + fileName);
        try {
            //存储文件在本地
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("上传文件失败" + e.getMessage());
            throw new RuntimeException("上传文件失败,服务器发生异常" + e);
        }

        /*
            更新当前用户的头像路径(web路径)
            http://localhost:8080/community/
         */
        //从hostHolder中获取当前user
        User user = hostHolder.getUser();
        //定义头像的web路径
        String headerUrl = domain + contextPath + "/user/header/" + fileName;
        //修改头像路径
        userService.updateHeader(user.getId(),headerUrl);
        //重定向到主页
        return "redirect:/index";
    }

    /**
     *  设置头像的web路径
     * @param fileName
     * @param response
     */
    @RequestMapping(path = "/header/{fileName}",method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response){
        //服务器存放路径
        fileName = uploadPath + "/" + fileName;
        //文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //响应图片
        response.setContentType("image/" + suffix);
        try (
                FileInputStream fis = new FileInputStream(fileName);
                OutputStream os = response.getOutputStream();
            ){
            byte [] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1){
                os.write(buffer,0,b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败" + e.getMessage());
        }
    }

    /**
     * 修改密码
     * @param oldPassword
     * @param newPassword
     * @param confirmPassword
     * @param model
     * @param ticket
     * @return
     */
    @RequestMapping(path = "/password",method = RequestMethod.POST)
    public String updatePassword(@RequestParam("old-password") String oldPassword,
                                 @RequestParam("new-password")String newPassword,
                                 @RequestParam("confirm-password")String confirmPassword,
                                 Model model,
                                 @CookieValue("ticket")String ticket){
        User user = hostHolder.getUser();
        if (CommunityUtil.md5(oldPassword + user.getSalt()).equals(user.getPassword())){
            if (!newPassword.equals(confirmPassword)){
                model.addAttribute("pwdMsg","两次输入的密码不同，请重新输入！");
                return "/site/setting";
            }else {
                newPassword = CommunityUtil.md5(newPassword + user.getSalt());
                userService.updataPassword(user.getId(),newPassword);
                userService.logout(ticket);
                return "redirect:/login";
            }
        }else {
            model.addAttribute("oldPwdMsg","原密码输入错误，请重新输入！");
            return "/site/setting";
        }

    }

    //个人主页
    @RequestMapping(path = "/profile/{userId}",method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("userId") int userId,Model model){
        User user = userService.findUserById(userId);
        if (user == null){
            throw new RuntimeException("该用户不存在!");
        }

        //用户
        model.addAttribute("user",user);
        //点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount",likeCount);

        //关注数量
        long followeeCount = followService.findFolloweeCount(userId,ENTITY_TYPE_USER);
        model.addAttribute("followeeCount",followeeCount);
        //粉丝数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER,userId);
        model.addAttribute("followerCount",followerCount);
        //是否已关注
        boolean hasFollowed = true;
        if (hostHolder.getUser() != null){
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(),ENTITY_TYPE_USER,userId);
        }

        model.addAttribute("hasFollowed",hasFollowed);
        return "/site/profile";
    }
}


